def generate_reportText(results,title):
    resData =f"========{title}========\n"
    # 年收益情况
    yearListRatio = results['yearListRatio']
    # print(yearListRatio)
    resData+=f"年份       周期收益     策略收益\n"
    for item in yearListRatio:
        resData+=f"{item['date']}       {item['close']}     {item['value']}\n"

    resData+="================================\n"
    resData += f"回测周期: {results['meta']['period']} \n"
    resData += f"时间跨度: {results['meta']['years']:.2f}年 (累计涨幅: {(results['performance']['dapan_ratio']*100):.2f}%)\n"
    resData += f"期末资产: {results['performance']['final_value']:.2f} (总收益: {(results['performance']['total_return']*100):.2f}%)\n"
    resData += f"年化收益: {(results['performance']['annualized_return']*100):.2f}% (胜率: {(results['trades']['winrate'] * 100):.2f}%)\n"
    resData += f"夏普比率: {results['performance']['sharpe_ratio']:.2f}% (最大回撤: {results['performance']['max_drawdown']:.2f}%)\n"
    resData += f"交易次数: {results['trades']['total']} (连胜: {results['trades']['streak_won']}  连败: {results['trades']['streak_lost']})\n"

    return resData


def generate_report(results, filename='backtest_report.html',title='',):
    """生成HTML可视化报告"""
    from jinja2 import Template
    import webbrowser
    
    # 报告模板
    template = """
    <!DOCTYPE html>
    <html>
    <head>
        <title>量化策略回测报告</title>
        <script src="./js/plotly-latest.min.js"></script>
        <link rel="stylesheet" type="text/css"  href="./css/layui.css">
        <style>
            body { font-family: Arial; margin: 20px }
            .card { border: 1px solid #ddd; padding: 15px; margin: 10px; border-radius: 5px }
            .flex { display: flex; flex-wrap: wrap }
            h2 { color: #333 }
            .titleData{
                background-color: #f9a28e;
                padding: 10px;
                border-radius: 10px;
                color: #fff;
                font-weight: 700;
            }
        </style>
    </head>
    <body>
       <h3 class="titleData">{{titleData}}</h3>
        <table class="layui-table">
            <tr>
                <td class="label">回测周期</td>
                <td colspan="3"> {{ results.meta.period }} ({{  "%.2f"|format(results.meta.years) }}年)</td>
            </tr>
            <tr>
                <td  class="label">期末资产</td>
                <td > {{ "%.2f"|format(results.performance.final_value) }} </td>
                <td  class="label">总交易次数</td>
                <td > {{ results.trades.total }}  <span class="layui-badge layui-bg-blue">连胜: {{results.trades.streak_won}}</span>
                 <span class="layui-badge ">连败: {{results.trades.streak_lost}}</span> </td>
            </tr>
            <tr>
                <td  class="label">累计收益率</td>
                <td >
                
                {{ "%.2f"|format(results.performance.total_return*100) }}%
                <span class="layui-badge layui-bg-gray">行情跌涨: {{ "%.2f"|format(results.performance.dapan_ratio *100)}}%</span>
                </td>
                <td  class="label">总盈亏</td>
                <td >  {{ "%.2f"|format(results.trades.pnl) }}</td>
            </tr>
            <tr>
                <td  class="label">年化收益率</td>
                <td > {{ "%.2f"|format(results.performance.annualized_return*100) }}%</td>
                <td  class="label">胜率</td>
                <td > {{ "%.2f"|format(results.trades.winrate * 100 ) }}%</td>
            </tr>
            <tr>
                <td  class="label">夏普比率</td>
                <td >{{ "%.2f"|format(results.performance.sharpe_ratio) }}</td>
                
                <td  class="label">平均盈亏</td>
                <td > {{ "%.2f"|format(results.trades.average) }}</td>
            </tr>
            <tr>
                <td  class="label">最大回撤</td>
                <td >{{ "%.2f"|format(results.performance.max_drawdown) }}% 
                (持续 {{ results.performance.max_drawdown_period }}根K线)</td>
                 <td  class="label">多空比例</td>
                <td > {{ "%.2f"|format(results.trades.long_ratio*100) }}% 多头</td>
            </tr>

        </table>
        

        <div class="layui-row">
  <div class="layui-col-xs6">
     <div id="returnsChart" style="width:100%;height:400px;"></div>
  </div>
  <div class="layui-col-xs6">
    <div id="returnsChart2" style="width:100%;height:400px;"></div>
  </div>
</div>

       
       
        <script>
            var returns = {{ returns_data }}
            Plotly.newPlot('returnsChart', [
            {
                x: returns.dates,
                y: returns.closes,
                type: 'line',
                name:'收盘价',
            }
            ], {title: '价格走势'});
            Plotly.newPlot('returnsChart2', [
            {
                x: returns.dates,
                y: returns.values,
                type: 'line',
                name:'资金'
            },
            ], {title: '资金走势'});

        </script>
    </body>
    </html>
    """
    # ;
    # 准备收益率曲线数据
    # returns_data = {
    #     'dates': list(results['returns']['monthly'].keys()),
    #     'values': list(results['returns']['monthly'].values())
    # }
    
    # 渲染报告
    html = Template(template).render(
        results=results,
        titleData = title,
        returns_data=results['returns']
    )
    
    with open(filename, 'w', encoding='utf-8') as f:
        f.write(html)
    
    # 自动打开报告
    webbrowser.open(filename)